import React, { useState, useEffect, useReducer } from "react";
import Header from "../../components/Header";
import { Cartlist, Cartedit, Cartdelete } from "../../http/api"
import { initState, reducer } from "../Login/user"
import have from '../../assets/img/have.jpeg'
import no from '../../assets/img/no.jpeg'
import "./shoplist.less"
import { Toast } from "_antd-mobile@2.3.4@antd-mobile";

export default function Shop() {
    //初始化数据
    const [list, setList] = useState([])
    const [state] = useReducer(reducer, initState)
    const [allChecked, setAllChecked] = useState(false);
    // 首先先定义一个变量isRequest ,默认是true 
    let isRequest = true;
    //请数据
    useEffect(() => {
        cartList()
    }, [])
    //请列表数据 
    const cartList = async () => {
        let res = await Cartlist({ uid: state.info.uid })
        if (res.data.code === 200) {
            let arr1 = res.data.list[0].content ? res.data.list[0].content : []
            let arr2 = res.data.list[1].content ? res.data.list[1].content : []
            let arrs = arr1.concat(arr2);
            //checked按钮
            arrs.forEach((item) => {
                let obj = list.find((i) => i.id === item.id);
                item.checked = obj ? obj.checked : false
            })
            setList(arrs)
            //打开开关
            isRequest = true
        }
    }
    // 点某一个的checked
    const changeOne = (index) => {
        list[index].checked = !list[index].checked;
        //修改list
        setList([...list]);
        //修改allChecked
        setAllChecked(list.every((item) => item.checked));
    };
    // 修改全选
    const changeAll = () => {
        let newAll = !allChecked;
        //修改全选
        setAllChecked(newAll);
        //修改list
        list.forEach((item) => {
            item.checked = newAll;
        });
        setList([...list]);
    };
    //数量增加
    const add = async (id) => {
        let res = await Cartedit({ id, type: 2 });
        if (res.data.code === 200) {
            // 修改成功之后，重新请求列表数据
            cartList();
        }
    };
    //7.数量减少
    const sub = async (id, num) => {
        if (num <= 1) {
            Toast.info("宝贝不能再少了");
            return;
        }
        //判断开关是否打开，开着，就发请求
        if (isRequest) {
            // 开关关掉
            isRequest = false;
            let res = await Cartedit({ id, type: 1 });
            if (res.data.code === 200) {
                // 修改成功之后，重新请求列表数据
                cartList();
            }
        }
    };
    // 计算总价
    let allPrice = list.reduce((val, item) => item.checked ? val += item.price * item.num : val, 0)
    //删除
    const del = async (id) => {
        let res = await Cartdelete({ id });
        if (res.data.code === 200) {
            cartList()
        }
    }
    return (
        <div>
            <Header title="购物车"></Header>
            {list.length > 0 ? <div className="shoplist">
                {
                    list.map((item, index) => (
                        <div key={item.id}>
                            <div className="shop">
                                <div onClick={() => changeOne(index)} >
                                    {
                                        item.checked ? <div className="icon"> <img src={have} alt="" /> </div> : <div className="icon"> <img src={no} alt="" /> </div>
                                    }
                                </div>
                                <img className="img" src={item.img} alt="" />
                                <div className="right">
                                    <span className="name">{item.goodsname}</span>
                                    <div className="search">
                                        <p>￥{item.price}</p>
                                        <div>
                                            <button onClick={() => sub(item.id, item.num)}>-</button>
                                            <span>{item.num}</span>
                                            <button onClick={() => add(item.id)}>+</button>
                                        </div>
                                        <button onClick={() => del(item.id)}>删除</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    ))
                }
                <div className="checked" onClick={() => changeAll()}>
                    是否全选：{allChecked ? <div className="icon"> <img src={have} alt="" /> </div> : <div className="icon"> <img src={no} alt="" /> </div>}
                    <span>总价：￥{allPrice.toFixed(2)}</span>
                </div>
            </div> : null}
        </div>
    )
}

